package com.jing.cloud.service.es;

import com.alibaba.fastjson.JSON;
import com.jing.cloud.service.user.bean.User;
import com.jing.cloud.service.util.keygen.IdUtil;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;

/**
 * Created by 29017 on 2017/9/23.
 */
public class EsTest {

    private static TransportClient client = new PreBuiltTransportClient(Settings.EMPTY);

    static {
        try {
            client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
        } catch (Exception e) {
        }
    }


    public static void main(String[] args) throws Exception {
        showtime();
        get();
        showtime();
    }

    private static void get() {
        GetResponse res = client.prepareGet("jim", "user", "118414614672182663").get();
        String map = res.getSourceAsString();
        System.out.println(map);
    }

    private static void search() {
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        client.prepareSearch("jim").setTypes("user").setQuery(builder);
    }

    private static void insert() {
        showtime();
        BulkRequestBuilder bulkRequestBuilder = client.prepareBulk();
        for (int i = 0; i < 1000000; i++) {
            User user = new User();
            user.setId(IdUtil.longId());
            user.setNickname("张三");
            user.setSex(1);
            user.setUserType(1);
            user.setState(1);
            user.forCreate();
            IndexRequestBuilder builder = client.prepareIndex("jim", "user", user.getId().toString()).setSource(JSON.toJSONString(user), XContentType.JSON);

            bulkRequestBuilder.add(builder);
        }
        showtime();
        bulkRequestBuilder.get();
        showtime();
    }

    private static long time = System.currentTimeMillis();

    private static void showtime() {
        long t2 = System.currentTimeMillis();
        System.out.println(t2 - time);
        time = t2;
    }
}
